package com.czk.gulimall.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * CompletableFuture的基本操作
 *
 * @Author:ChenZhangKun
 * @Date: 2022/2/10 11:02
 */
public class CompletableFutureTest {
    private static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //
        CompletableFuture.runAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread().getName());
            int i = 10 / 2;
            System.out.println(i);
            // 传入指定的线程池
        }, executor);
        // 可以返回结果
        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread().getName());
            int i = 10 / 2;
            return i;
        }, executor);
        System.out.println(integerCompletableFuture.get());
        // 可以回调
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread().getName());
            int i = 10 / 2;
            return i;
        }, executor).whenComplete((res, exception) -> {
            // 结果
            System.out.println(res);
            // 异常
            System.out.println(exception);
        });

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread().getName());
            int i = 10 / 0;
            return i;
        }, executor).whenComplete((res, exception) -> {
            // 结果
            System.out.println(res);
            // 异常
            System.out.println(exception);
        }).exceptionally(throwable -> {
            // 感知异常，返回默认值
            return 10;
        });
        // 返回默认值
        System.out.println(future2.get());

        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread().getName());
            int i = 10 / 1;
            return i;
            // 对返回结果的·处理
        }, executor).handle((res, throwable) -> {
            if (res != null) {
                return res * 2;
            }
            if (throwable != null) {
                return 0;
            }
            return 1;
        });
        System.out.println(future3.get());
    }

}
